/*
 * @author Chris
 * @since 2023/2/8 19:31
 *
 * @brief    The project will ...
 *
 * @note     ...
 *
 * @warning  Do not to ...
 *
 * Change Logs:
 *   Date           Author       Notes
 *   2023-02-08     Chris        the first version
 *
 */
#include "8052.h"

#define KEY_IN_1 P2_4
#define KEY_IN_2 P2_5
#define KEY_IN_3 P2_6
#define KEY_IN_4 P2_7
#define KEY_OUT_1 P2_3
#define KEY_OUT_2 P2_2
#define KEY_OUT_3 P2_1
#define KEY_OUT_4 P2_0

// 按键矩阵编号与标准键盘映射
unsigned char __code keyboardMap[4][4] = {
        {0x31, 0x32, 0x33, 0x26},   // 1、2、3、上
        {0x34, 0x35, 0x36, 0x25},   // 4、5、6、左
        {0x37, 0x38, 0x39, 0x28},   // 7、8、9、下
        {0x30, 0x1B, 0x0D, 0x27},   // 0、ESC、ENTER、右
};

unsigned char keySta[4][4] = {
        {1, 1, 1, 1},
        {1, 1, 1, 1},
        {1, 1, 1, 1},
        {1, 1, 1, 1},
};

extern void KeyAction(unsigned char keycode);

void KeyDriver() {
    static unsigned char keyBak[4][4] = {
            {1, 1, 1, 1},
            {1, 1, 1, 1},
            {1, 1, 1, 1},
            {1, 1, 1, 1},
    };

    for (int i = 0; i < 4; ++i) {
        for (int j = 0; j < 4; ++j) {
            if (keyBak[i][j] != keySta[i][j]) {
                if (keyBak[i][j] == 1) {
                    KeyAction(keyboardMap[i][j]);
                }
                keyBak[i][j] = keySta[i][j];
            }
        }
    }
}

void KeyScan() {
    static unsigned char row = 0;
    static unsigned char keyBuf[4][4] = {
            {0xFF, 0xFF, 0xFF, 0xFF},
            {0xFF, 0xFF, 0xFF, 0xFF},
            {0xFF, 0xFF, 0xFF, 0xFF},
            {0xFF, 0xFF, 0xFF, 0xFF},
    };

    keyBuf[row][0] = (keyBuf[row][0] << 1) | KEY_IN_1;
    keyBuf[row][1] = (keyBuf[row][1] << 1) | KEY_IN_2;
    keyBuf[row][2] = (keyBuf[row][2] << 1) | KEY_IN_3;
    keyBuf[row][3] = (keyBuf[row][3] << 1) | KEY_IN_4;

    for (int i = 0; i < 4; ++i) {
        if ((keyBuf[row][i] & 0x0F) == 0) {
            keySta[row][i] = 0;
        } else if ((keyBuf[row][i] & 0x0F) == 0x0F) {
            keySta[row][i] = 1;
        }
    }
    row++;
    row &= 0x03;
    P2 = P2 & 0xF0 | (~(1 << (3 - row)));

}